// ==UserScript==
// @name			Enhanced Gifter
// @description		Gets rid of loot you do not want
// @include   		http://apps.facebook.com/inthemafia/*
// @include   		http://apps.new.facebook.com/inthemafia/*
// @version			9.29.09
// ==/UserScript==

GM_registerMenuCommand('EG - Add as recipient', saveRecipient);

window.setInterval(function (){setupPage()}, 4000);

try
{//update checker by Jarett @ http://userscripts.org/scripts/show/20145
	function updateCheck(forced)
	{
		if ((forced) || (parseInt(GM_getValue('SUC_last_update', '0')) + 86400000 <= (new Date().getTime())))
		{
			try
			{
				GM_xmlhttpRequest(
				{
					method: 'GET',
					url: 'http://userscripts.org/scripts/source/52429.meta.js?'+new Date().getTime(),
					headers: {'Cache-Control': 'no-cache'},
					onload: function(resp)
					{
						var local_version, remote_version, rt, script_name;
						
						rt=resp.responseText;
						GM_setValue('SUC_last_update', new Date().getTime()+'');
						remote_version=parseInt(/@uso:version\s*(.*?)\s*$/m.exec(rt)[1]);
						local_version=parseInt(GM_getValue('SUC_current_version', '-1'));
						if(local_version!=-1)
						{
							script_name = (/@name\s*(.*?)\s*$/m.exec(rt))[1];
							GM_setValue('SUC_target_script_name', script_name);
							if (remote_version > local_version)
							{
								if(confirm('There is an update available for the Greasemonkey script "'+script_name+'."\nWould you like to go to the install page now?'))
								{
									GM_openInTab('http://userscripts.org/scripts/show/52429');
									GM_setValue('SUC_current_version', remote_version);
								}
							}
							else if (forced)
								alert('No update is available for "'+script_name+'."');
						}
						else
							GM_setValue('SUC_current_version', remote_version+'');
					}
				});
			}
			catch (err)
			{
				if (forced)
					alert('An error occurred while checking for updates:\n'+err);
			}
		}
	}
	GM_registerMenuCommand(GM_getValue('SUC_target_script_name', 'EG') + ' - Manual Update Check', function()
	{
		updateCheck(true);
	});
	updateCheck(false);
}
catch(err){}

function setupPage()
{
	if (document.getElementById('app10979261223_gift_send'))
	{
		document.getElementById('app10979261223_gift_send').id = 'enhanced';
		var sexyElements = document.getElementsByClassName('sexy_button gift_category_button');
		var leftBox = sexyElements[0].parentNode;
		leftBox.setAttribute('id', 'leftBox');
		leftBox.style.width = '170px';
		leftBox.parentNode.parentNode.parentNode.style.height = '700px';
		leftBox.nextSibling.nextSibling.childNodes[1].style.height = '700px';
		sexyElements[2].parentNode.removeChild(sexyElements[2]);
		sexyElements[1].parentNode.removeChild(sexyElements[1]);
		sexyElements[0].parentNode.removeChild(sexyElements[0]);
		var stockDiv = document.createElement("DIV");
		stockDiv.style.width = '170px';
		stockDiv.style.height = '165px';
		stockDiv.appendChild(document.createTextNode('============= '));
		stockDiv.appendChild(document.createTextNode("Category:"));
		stockDiv.appendChild(makeSexyButton('Loot', '', viewLoot, '130px'));
		stockDiv.appendChild(makeSexyButton('Collections', '', viewCollections, '130px'));
		stockDiv.appendChild(makeSexyButton('Boosts', '', viewBoosts, '130px'));
		stockDiv.appendChild(makeSexyButton('All', '', viewAll, '130px'));
		leftBox.appendChild(stockDiv);
		viewLoot();
		var enhancedGifterDiv = document.createElement("DIV");
		enhancedGifterDiv.style.width = '170px';
		enhancedGifterDiv.style.height = '285px';
		leftBox.appendChild(enhancedGifterDiv);
		var recipientList = document.createElement("SELECT");
		recipientList.style.width = '142px';
		recipientList.style.marginBottom = '4px';
		recipientList.setAttribute('id', 'recipientList');	
		var userNames = eval(GM_getValue('userNames', []));
		var userIDs = eval(GM_getValue('userIDs', []));
		for (var i = 0; i < userNames.length; i++)
		{
			var recipient = document.createElement("OPTION");
			recipient.setAttribute('id', userIDs[i]);
			recipient.setAttribute('title', userIDs[i]);
			recipient.textContent = userNames[i];
			recipientList.appendChild(recipient);
		}		
		enhancedGifterDiv.appendChild(document.createTextNode('============= '));
		enhancedGifterDiv.appendChild(document.createTextNode("Recipient:__________"));
		enhancedGifterDiv.appendChild(makeSexyButton('Delete', 'Delete the currently displayed recipient', deleteRecipient, '55px'));
		enhancedGifterDiv.appendChild(makeSexyButton('Default', 'Make the currently displayed recipient default', defaultRecipient, '55px'));	
		enhancedGifterDiv.appendChild(recipientList);
		enhancedGifterDiv.appendChild(document.createTextNode('============= '));
		enhancedGifterDiv.appendChild(document.createTextNode("Action:"));
		enhancedGifterDiv.appendChild(makeSexyButton('Execute', 'Sends the loot items', executeAll, '130px'));
		enhancedGifterDiv.appendChild(makeSexyButton('Execute Category', 'Sends the currently displayed loot items', executeCategory, '130px'));
		enhancedGifterDiv.appendChild(makeSexyButton('Execute Single', 'Sends the currently highlighted loot item', executeSingle, '130px'));
		enhancedGifterDiv.appendChild(makeSexyButton('Save Quantities', 'Saves all values in the text boxes', saveKeeps, '130px'));
		enhancedGifterDiv.appendChild(makeSexyButton('Reset Quantities', 'Resets all the text boxes to "ALL" and saves', resetKeeps, '130px'));
		enhancedGifterDiv.childNodes[2].style.marginRight = '8px';
		var logDiv = document.createElement("DIV");
		logDiv.style.width = '170px';
		logDiv.style.height = '245px';
		logDiv.style.overflow = 'auto';
		logDiv.setAttribute('id', 'logDiv');
		leftBox.appendChild(logDiv);
		var divElements = document.getElementsByTagName('DIV');
		for (var i = 0; i < divElements.length; i++)
		{
			if (/app10979261223_item_box/.test(divElements[i].id))
			{
				var newText = document.createTextNode('Keep:');
				var newInputBox = document.createElement('INPUT');
				newInputBox.style.background = "#000000";
				newInputBox.style.color = "#BCD2EA";
				newInputBox.style.textAlign = "right";
				newInputBox.size = "2";
				newInputBox.className = "EG";
				newInputBox.id = trim(divElements[i].childNodes[1].textContent) + ":" + divElements[i].id.charAt(24) + ":" + divElements[i].id.substr(26);
				divElements[i].style.height = "150px";
				divElements[i].appendChild(newText);	
				divElements[i].appendChild(newInputBox);
			}
		}
		var keeps = eval(GM_getValue('keeps', []));
		for (var i = 0; i < keeps.length; i++)
		{
			try
			{
				document.getElementById(keeps[i].substr(0, keeps[i].lastIndexOf(':'))).value = keeps[i].substr(keeps[i].lastIndexOf(':') + 1);
			}
			catch(err)
			{}
		}
		inputElements = document.getElementsByClassName('EG');
		for (var i = 0; i < inputElements.length; i++)
		{
			if (inputElements[i].value == '')
			{
				inputElements[i].value = 'All';
			}
		}		
	}
	var allElements = document.getElementsByClassName('tab_content');	
	for (var i = 0; i < allElements.length; i++)
	{
		if (allElements[i].textContent.match('Profile') == 'Profile')
		{
			if (allElements[i].parentNode.parentNode.lastChild.textContent != 'Add as recipient')
			{
				var userID;
				var userName;
				var content=document.getElementById('app10979261223_content_row');
				var as=content.getElementsByTagName('a');
				for(j = 0; j < as.length; j++)
				{
					if(as[j].innerHTML=='Profile')
					{
						var match=/[;&]user=(\d+)/.exec(as[j].href).toString();
						var comma = match.indexOf(",");
						comma++;
						userID = match.substring(comma);
						userName = as[j].parentNode.textContent.substr(8, as[j].parentNode.textContent.indexOf(")") - 8);
						var recipientListItem = document.createElement('LI');
						recipientListItem.className = 'tab_off tab_last';
						var recipientDivision = document.createElement('DIV');
						recipientDivision.className = 'tab_content';
						recipientDivision.style.width = '220px';
						var recipientAnchor = document.createElement('A');
						recipientAnchor.textContent = 'Add as recipient';
						recipientAnchor.addEventListener('click', function(event){saveRecipient();}, true);
						var recipientNameBox = document.createElement('INPUT');
						recipientNameBox.style.background = "#000000";
						recipientNameBox.style.color = "#BCD2EA";
						recipientNameBox.size = "30";
						recipientNameBox.className = "EG";
						recipientNameBox.title = userID;
						recipientNameBox.id = 'recipientNameBox';
						recipientNameBox.value = userName;
						recipientDivision.appendChild(recipientAnchor);
						recipientDivision.appendChild(recipientNameBox);
						recipientListItem.appendChild(recipientDivision);
						as[j].parentNode.parentNode.parentNode.appendChild(recipientListItem);
					}
				}
			}
		}
	}
}

function makeSexyButton(text, tip, funct, size)
{
	var sexyButton = document.createElement("A");
	sexyButton.textContent = text;
	sexyButton.title = tip;
	sexyButton.className = "sexy_button gift_category_button";
	sexyButton.addEventListener('click', function(event){funct();}, true);
	sexyButton.style.width = size;
	return sexyButton;
}

function viewLoot()
{
	document.getElementById('app10979261223_table_loot').style.display = 'block';
	document.getElementById('app10979261223_table_collection').style.display = 'none';
	document.getElementById('app10979261223_table_expendables').style.display = 'none';
	document.getElementById('app10979261223_gift_category').value = '1';
}

function viewCollections()
{
	document.getElementById('app10979261223_table_loot').style.display = 'none';
	document.getElementById('app10979261223_table_collection').style.display = 'block';
	document.getElementById('app10979261223_table_expendables').style.display = 'none';
	document.getElementById('app10979261223_gift_category').value = '0';
}

function viewBoosts()
{
	document.getElementById('app10979261223_table_loot').style.display = 'none';
	document.getElementById('app10979261223_table_collection').style.display = 'none';
	document.getElementById('app10979261223_table_expendables').style.display = 'block';
	document.getElementById('app10979261223_gift_category').value = '2';
}

function viewAll()
{
	document.getElementById('app10979261223_table_loot').style.display = 'block';
	document.getElementById('app10979261223_table_collection').style.display = 'block';
	document.getElementById('app10979261223_table_expendables').style.display = 'block';
}

function executeAll()
{
	var sendList = new Array(new Array(), new Array(), new Array(), new Array());
	inputElements = document.getElementsByClassName('EG');
	for (var i = 0; i < inputElements.length; i++)
	{
		if (trim(inputElements[i].parentNode.childNodes[5].textContent).substr(1) - inputElements[i].value > 0)
		{
			var index = sendList[0].length;
			sendList[0][index] = inputElements[i].id.substr(0, inputElements[i].id.indexOf(":"));									//name
			sendList[1][index] = inputElements[i].id.charAt(inputElements[i].id.indexOf(":") + 1);									//category
			sendList[2][index] = inputElements[i].id.substr(inputElements[i].id.lastIndexOf(":") + 1);								//id
			sendList[3][index] = trim(inputElements[i].parentNode.childNodes[5].textContent).substr(1) - inputElements[i].value;	//gifting amount
		}
	}
	if (sendList[0][0] == null)
	{
		alert('There is nothing to send');
	}
	else
	{
		setupGiftingFrame();
		send(sendList);
	}
}

function executeCategory()
{
	var category;
	if (document.getElementById('app10979261223_table_expendables').style.display == 'block')
	{category = 2;}
	if (document.getElementById('app10979261223_table_collection').style.display == 'block')
	{category = 0;}
	if (document.getElementById('app10979261223_table_loot').style.display == 'block')
	{category = 1;}
	var sendList = new Array(new Array(), new Array(), new Array(), new Array());
	inputElements = document.getElementsByClassName('EG');
	for (var i = 0; i < inputElements.length; i++)
	{
		if (trim(inputElements[i].parentNode.childNodes[5].textContent).substr(1) - inputElements[i].value > 0)
		{
			if (inputElements[i].id.charAt(inputElements[i].id.indexOf(":") + 1) == category)
			{
				var index = sendList[0].length;
				sendList[0][index] = inputElements[i].id.substr(0, inputElements[i].id.indexOf(":"));									//name
				sendList[1][index] = inputElements[i].id.charAt(inputElements[i].id.indexOf(":") + 1);									//category
				sendList[2][index] = inputElements[i].id.substr(inputElements[i].id.lastIndexOf(":") + 1);								//id
				sendList[3][index] = trim(inputElements[i].parentNode.childNodes[5].textContent).substr(1) - inputElements[i].value;	//gifting amount
			}
		}
	}
	if (sendList[0][0] == null)
	{
		alert('There is nothing to send');
	}
	else
	{
		setupGiftingFrame();
		send(sendList);
	}
}

function executeSingle()
{
	var sendList = new Array(new Array(), new Array(), new Array(), new Array());
	for (var i = 0; i < inputElements.length; i++)
	{
		if (inputElements[i].parentNode.style.border == '1px solid rgb(255, 255, 0)')
		{
			sendList[0][0] = inputElements[i].id.substr(0, inputElements[i].id.indexOf(":"));									//name
			sendList[1][0] = inputElements[i].id.charAt(inputElements[i].id.indexOf(":") + 1);									//category
			sendList[2][0] = inputElements[i].id.substr(inputElements[i].id.lastIndexOf(":") + 1);								//id
			sendList[3][0] = trim(inputElements[i].parentNode.childNodes[5].textContent).substr(1) - inputElements[i].value;	//gifting amount
		}
	}
	if (sendList[0][0] == null)
	{
		alert('No item is selected');
	}
	else
	{
		alert(sendList[0][0] + ' is selected');
		setupGiftingFrame();
		send(sendList);
	}
}

function setupGiftingFrame()
{
	var logDiv = document.getElementById('logDiv');
	var sentList = document.createElement("DIV");
	sentList.setAttribute("id","sentList");
	var sentItem = document.createElement("DIV");
	sentItem.appendChild(document.createTextNode(' '));
	sentList.appendChild(sentItem);	
	logDiv.appendChild(sentList);
	var giftingFrame = document.createElement("IFRAME");
  	giftingFrame.setAttribute("id","giftingFrame"); 
  	giftingFrame.style.width = 10+"px"; 
  	giftingFrame.style.height = 10+"px"; 
  	logDiv.appendChild(giftingFrame);
}

function send(sendList)
{
	var recipientList = document.getElementById('recipientList');
	var userID = recipientList.childNodes[recipientList.selectedIndex].id;
	var giftingFrame = document.getElementById('giftingFrame');
	var sentList = document.getElementById('sentList');
	var numberOfItems = sendList[0].length;
	for (var i = 0; i < sendList[0].length; i++)
	{
		if (sendList[3][i] > 0)
		{
			if (sentList.lastChild.textContent.indexOf(sendList[0][i]) == -1)
			{
				var sentItem = document.createElement("DIV");
				sentItem.appendChild(document.createTextNode(sendList[3][i] + ' ' + sendList[0][i]));
				sentList.appendChild(sentItem);
			}
			sendList[3][i]--;
			GM_log('sending ' + sendList[0][i] + " to " + userID);
			giftingFrame.setAttribute("src", 'http://apps.facebook.com/inthemafia/remote/html_server.php?xw_controller=gift&' + 'recipients[0]=' + userID + '&gift_category=' + sendList[1][i] + '&gift_id=' + sendList[2][i] + '&gift_key=' + document.getElementById('app10979261223_gift_key').value + '&xw_action=send');
			window.setTimeout(function() {send(sendList)}, 4000);
			break;
		}
		else
		{			
			if (i == sendList[0].length - 1)
			{
				var sentItem = document.createElement("DIV");
				sentItem.appendChild(document.createTextNode('DONE SENDING'));
				sentList.appendChild(sentItem);
				window.setTimeout(refreshGiftingPage, 4000)
			}
		}
	}	
}

function resetKeeps()
{
	inputElements = document.getElementsByClassName('EG');
	for (var i = 0; i < inputElements.length; i++)
	{
		inputElements[i].value = 'All';
	}
	saveKeeps();
}
	
function saveKeeps()
{
	inputElements = document.getElementsByClassName('EG');
	var keeps = new Array();
	for (var i = 0; i < inputElements.length; i++)
	{
		keeps[i] = inputElements[i].id + ':' + inputElements[i].value;
	}
	GM_setValue('keeps', uneval(keeps));
	alert('Quantities saved');
}

function saveRecipient()
{
	var inMafia = false;
	var AE = document.getElementsByTagName('A')
	for (var i = 0; i < AE.length; i++)
	{
		if (AE[i].textContent == 'Remove from Mafia')
		{	
			inMafia = true;
		}
	}
	if (inMafia)
	{	
		var recipientNameBox = document.getElementById('recipientNameBox');
		var userNames = eval(GM_getValue('userNames', []));
		var userIDs = eval(GM_getValue('userIDs', []));
		var newSpot = userNames.length;
		var isDuplicate = false;
		for (var i = 0; i < userIDs.length; i++)
		{
			if (recipientNameBox.title == userIDs[i])
			{
				isDuplicate = true;
			}
		}
		if (isDuplicate)
		{
			alert('You have already saved this recipient');
		}
		else
		{
			userNames[newSpot] = recipientNameBox.value;
			userIDs[newSpot] = recipientNameBox.title;
			GM_setValue('userNames', uneval(userNames));
			GM_setValue('userIDs', uneval(userIDs));
			alert('Mafia Name:' + recipientNameBox.value + '\nMafia ID:' + recipientNameBox.title + '\nNow going to the gifting page.');
			window.location.href = 'http://apps.facebook.com/inthemafia/remote/html_server.php?xw_controller=gift&xw_action=view&xw_city=2';
		}
	}
	else
	{
		alert('Mafia is not a member of your family\nThey cannot be added as a recipient');
	}
}

function deleteRecipient()
{
	var recipientList = document.getElementById('recipientList');
	recipientList.remove(recipientList.selectedIndex);
	var userNames = new Array();
	var userIDs = new Array();
	for (var i = 0; i < recipientList.length; i++)
	{
		userNames[i] = recipientList.childNodes[i].value;
		userIDs[i] = recipientList.childNodes[i].id;
	}
	GM_setValue('userNames', uneval(userNames));
	GM_setValue('userIDs', uneval(userIDs));	
}

function defaultRecipient()
{
	var recipientList = document.getElementById('recipientList');
	var userNames = new Array();
	var userIDs = new Array();
	userNames[0] = recipientList.childNodes[recipientList.selectedIndex].value;
	userIDs[0] = recipientList.childNodes[recipientList.selectedIndex].id;
	for (var i = 0; i < recipientList.length; i++)
	{
		if (i == recipientList.selectedIndex)
		{
			continue;
		}
		else
		{
			userNames[userNames.length] = recipientList.childNodes[i].value;
			userIDs[userIDs.length] = recipientList.childNodes[i].id;
		}
	}
	GM_setValue('userNames', uneval(userNames));
	GM_setValue('userIDs', uneval(userIDs));
}

function refreshGiftingPage()
{
	allElements = document.getElementsByTagName('A');
	for (var i = 0; i < allElements.length; i++)
	{
		if (allElements[i].text == 'Gifting')
		{
			clickElement(allElements[i]);
		}
	}
}

function clickElement(elt)
{
	var evt = document.createEvent('MouseEvents');
	evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
	elt.dispatchEvent(evt);
}

function trim(str)
{
	return str.replace(/^\s+|\s+$/g,"");
}